package com.mrd.shiptask_shipowner.activity;

import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import com.mrd.shiptask_shipowner.R;
import com.mrd.shiptask_shipowner.constants.HttpConstant;
import com.mrd.shiptask_shipowner.constants.database.DBUtil;
import com.mrd.shiptask_shipowner.serviecs.BizNetworkService;
import com.mrd.shiptask_shipowner.serviecs.initdatadao.InitDatasDaoImpl;
import com.mrd.shiptask_shipowner.shiareutil.SharePreferenceUtil;
import com.mrd.shiptask_shipowner.unit_tools.ButtonTool;
import com.mrd.shiptask_shipowner.unit_tools.DatasTools;
import com.mrd.shiptask_shipowner.unit_tools.FunctionOfActivity;
import com.mrd.shiptask_shipowner.unit_tools.HttpUrlConstant;
import com.mrd.shiptask_shipowner.unit_tools.SysApplication;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MakeToOrderActivity extends Activity {
	private MakeToOrderActivity THIS = MakeToOrderActivity.this;
	private Button acceptbt, refusebt, backToBeforeBt3;
	private TextView routetv, goodstv, loadingCapacitytv, packingMethodtv,
			ownertv, contactstv, contactInformationtv, billingMethodtv,
			unitPricetv, constructionFeetv, yjsfhsptv, closingDatetv,
			lossRatetv, zxcsjhjtv, detentionChargetv, cbdwyqtv,
			loadingRequirementstv, remarkstv;

	private ProgressDialog pro;
	private String thisApplyId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.make_to_order_main);
		setIniteView();
		SysApplication.getInstance().addActivity(this);
	}

	private void setIniteView() {
		TextView topTitleTv = (TextView) findViewById(R.id.topTitleTv);
		topTitleTv.setText("货运申请");
		// TODO Auto-generated method stub
		routetv = (TextView) findViewById(R.id.routetv);// 航线
		goodstv = (TextView) findViewById(R.id.goodstv);// 货物
		loadingCapacitytv = (TextView) findViewById(R.id.loadingCapacitytv);// 装载量
		packingMethodtv = (TextView) findViewById(R.id.packingMethodtv);// 包装方式
		ownertv = (TextView) findViewById(R.id.ownertv);// 货主
		contactstv = (TextView) findViewById(R.id.contactstv);// 联系人
		contactInformationtv = (TextView) findViewById(R.id.contactInformationtv);// 联系方式
		billingMethodtv = (TextView) findViewById(R.id.billingMethodtv);// 计费方式
		unitPricetv = (TextView) findViewById(R.id.unitPricetv);// 单价
		constructionFeetv = (TextView) findViewById(R.id.constructionFeetv);// 运价是否含港建费
		yjsfhsptv = (TextView) findViewById(R.id.yjsfhsptv);// 运价是否含税票
		closingDatetv = (TextView) findViewById(R.id.closingDatetv);// 装运截止日期
		lossRatetv = (TextView) findViewById(R.id.lossRatetv);// 损耗费
		zxcsjhjtv = (TextView) findViewById(R.id.zxcsjhjtv);// 装卸船时间合计
		detentionChargetv = (TextView) findViewById(R.id.detentionChargetv);// 滞船费
		cbdwyqtv = (TextView) findViewById(R.id.cbdwyqtv);// 船舶吨位要求
		loadingRequirementstv = (TextView) findViewById(R.id.loadingRequirementstv);// 装载要求
		remarkstv = (TextView) findViewById(R.id.remarkstv);// 备注
		/**
		 * 赋值到页面上
		 */
		// 如果是推送进来的
		if (getIntent().hasExtra("getPushValueOfKey")) {
			thisApplyId = getIntentExtraValue("getPushValueOfKey");
			setInitDatas();
		} else {
			thisApplyId = getIntentExtraValue("getId");
			intoValueToTextView();
		}
		acceptbt = (Button) findViewById(R.id.acceptbt);// 接受
		refusebt = (Button) findViewById(R.id.refusebt);// 拒绝
		backToBeforeBt3 = (Button) findViewById(R.id.backToBeforeBt3);// 返回
		acceptbt.setOnClickListener(socl);
		refusebt.setOnClickListener(socl);
		backToBeforeBt3.setOnClickListener(socl);
		ButtonTool
				.onClickButtonStyle(THIS, new Button[] { acceptbt, refusebt });
	}

	private final OnClickListener socl = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			switch (arg0.getId()) {
			case R.id.acceptbt:
				try {
					new AlertDialog.Builder(THIS)
							.setTitle("提示")
							.setMessage("是否确定接受该货运申请？")
							.setIcon(android.R.drawable.ic_dialog_info)
							.setPositiveButton("接受",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											try {
												InitDatasDaoImpl
														.acceptMakeToOrderAction(
																THIS,
																thisApplyId);
											} catch (Exception e) {

											}
										}
									}).setNegativeButton("取消", null).show();
				} catch (Exception e) {
				}
				break;
			case R.id.refusebt:
				try {
					new AlertDialog.Builder(THIS)
							.setTitle("提示")
							.setMessage("是否确定拒绝该货运申请？")
							.setIcon(android.R.drawable.ic_dialog_info)
							.setPositiveButton("拒绝",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											try {
												InitDatasDaoImpl
														.refuseMakeToOrderAction(
																THIS,
																thisApplyId);
											} catch (Exception e) {

											}
										}
									}).setNegativeButton("取消", null).show();
				} catch (Exception e) {
				}
				break;
			case R.id.backToBeforeBt3:
				finish();
				break;
			default:
				break;
			}
		}
	};

	private void intoValueToTextView() {
		// TODO Auto-generated method stub
		try {
			String route = getIntentExtraValue("getStartPort") + "-"
					+ getIntentExtraValue("getEndPort");
			String goods = getIntentExtraValue("getCargoName");
			String carryingCapacity = getIntentExtraValue("getRAmount")
					+ getIntentExtraValue("getCargoUnits");
			String packingType = getIntentExtraValue("getPackingType");

			String accountMethod = getIntentExtraValue("getAccountMethod");
			String expectPrice = getIntentExtraValue("getExpectPrice");
			String includePCF = getIntentExtraValue("getIncludePcf");
			String fareTax = getIntentExtraValue("getFareTax");
			String consignorCompany = getIntentExtraValue("getConsignorCompany");

			String consignor = getIntentExtraValue("getConsignor");
			String contact = getIntentExtraValue("getContact");
			String code = getIntentExtraValue("getCode");
			String loadTime = getIntentExtraValue("getLoadTime");
			String lossRate = getIntentExtraValue("getLossrate");
			String loadUseTime = getIntentExtraValue("getLoadUseTime") + "天";
			String demurrage = getIntentExtraValue("getDemurrage") + "元/吨/天";
			String shipTonnages = getIntentExtraValue("getShipTonnages");
			String loadRequire = getIntentExtraValue("getLoadRequire");
			String remark = getIntentExtraValue("getRemark");

			routetv.setText(route);// 航线
			goodstv.setText(goods);// 货物
			loadingCapacitytv.setText(carryingCapacity);// 装载量
			packingMethodtv.setText(packingType);// 包装方式
			ownertv.setText(consignorCompany);// 货主
			contactstv.setText(consignor);// 联系人
			contactInformationtv.setText(contact);// 联系方式
			billingMethodtv.setText(accountMethod);// 计费方式
			unitPricetv.setText(expectPrice);// 单价
			constructionFeetv.setText(includePCF);// 运价是否含港建费
			yjsfhsptv.setText(fareTax);// 运价是否含税票
			closingDatetv.setText(loadTime);// 装运截止日期
			if (lossRate.length() > 0) {
				// 加上千分号
				lossRate = lossRate + "‰";
			}
			lossRatetv.setText(lossRate);// 损耗费
			zxcsjhjtv.setText(loadUseTime);// 装卸船时间合计
			detentionChargetv.setText(demurrage);// 滞船费
			cbdwyqtv.setText(shipTonnages);// 船舶吨位要求
			loadingRequirementstv.setText(loadRequire);// 装载要求
			remarkstv.setText(remark);// 备注
		} catch (Exception e) {

		}

	}

	private String getIntentExtraValue(String key) {
		try {
			String value = getIntent().hasExtra(key) == false ? ""
					: getIntent().getStringExtra(key);
			if (value.length() <= 0) {
				return "-";
			}
			return value;
		} catch (Exception e) {
			return "-";
		}
	}

	private void setInitDatas() {
		try{
		// TODO Auto-generated method stub
		pro = new ProgressDialog(THIS);
		pro.setMessage("正在为您加载内容信息，请稍候");
		pro.show();
		HashMap<String, Object> param = new HashMap<String, Object>();
		param.put("ship_id", (new SharePreferenceUtil(THIS,
				HttpConstant.SAVE_USER)).getShip_id());
		param.put("applyId", thisApplyId);
		new Thread(new BizNetworkService(THIS, handler,
				HttpUrlConstant.INIT_MAKETOORDER_BY_ID, param)).start();
		}catch(Exception e){
			pro.dismiss();
		}
	}

	private void initDatasOfPush(String result) {
		// TODO Auto-generated method stub
		try {
			JSONObject job = new JSONObject(result);
			String route = DatasTools.getJsonValue(job, "startPort") + "-"
					+ DatasTools.getJsonValue(job, "endPort");
			String goods = DatasTools.getJsonValue(job, "cargoName");
			String carryingCapacity = DatasTools
					.getJsonValue(job, "rAmount")
					+ DatasTools.getJsonValue(job, "cargoUnits");
			String packingType = DatasTools.getJsonValue(job, "packingType");

			String accountMethod = DatasTools.getJsonValue(job,
					"accountMethod");
			String expectPrice = DatasTools.getJsonValue(job, "expectPrice");
			String includePCF = DatasTools.getJsonValue(job, "includePCF");
			String fareTax = DatasTools.getJsonValue(job, "fareTax");
			String consignorCompany = DatasTools.getJsonValue(job,
					"consignorCompany");

			String consignor = DatasTools.getJsonValue(job, "consignor");
			String contact = DatasTools.getJsonValue(job, "contact");
			String code = DatasTools.getJsonValue(job, "code");
			String loadTime = DatasTools.getJsonValue(job, "loadTime");
			String lossRate = DatasTools.getJsonValue(job, "lossRate");
			String loadUseTime = DatasTools.getJsonValue(job, "loadUseTime")
					+ "天";
			String demurrage = DatasTools.getJsonValue(job, "demurrage")
					+ "元/吨/天";
			String shipTonnages = DatasTools.getJsonValue(job,
					"shipTonnages");
			String loadRequire = DatasTools.getJsonValue(job, "loadRequire");
			String remark = DatasTools.getJsonValue(job, "remark");

			routetv.setText(route);// 航线
			goodstv.setText(goods);// 货物
			loadingCapacitytv.setText(carryingCapacity);// 装载量
			packingMethodtv.setText(packingType);// 包装方式
			ownertv.setText(consignorCompany);// 货主
			contactstv.setText(consignor);// 联系人
			contactInformationtv.setText(contact);// 联系方式
			billingMethodtv.setText(accountMethod);// 计费方式
			unitPricetv.setText(expectPrice);// 单价
			constructionFeetv.setText(includePCF);// 运价是否含港建费
			yjsfhsptv.setText(fareTax);// 运价是否含税票
			closingDatetv.setText(loadTime);// 装运截止日期
			if (lossRate.length() > 0) {
				// 加上千分号
				lossRate = lossRate + "‰";
			}
			lossRatetv.setText(lossRate);// 损耗费
			zxcsjhjtv.setText(loadUseTime);// 装卸船时间合计
			detentionChargetv.setText(demurrage);// 滞船费
			cbdwyqtv.setText(shipTonnages);// 船舶吨位要求
			loadingRequirementstv.setText(loadRequire);// 装载要求
			remarkstv.setText(remark);// 备注
		} catch (Exception e) {

		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 请求结果处理
	 */
	@SuppressLint("HandlerLeak")
	public Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			try {
				pro.dismiss();
				Bundle data = msg.getData();
				if (!data.isEmpty()) {
					try {
						switch (msg.what) {
						case HttpUrlConstant.INIT_MAKETOORDER_BY_ID:
							FunctionOfActivity.makeToaskShow(THIS,
									data.getString("msg"));
							if ("isPass"
									.equals(data.getString("submit_result"))) {
								initDatasOfPush(data.getString("result"));
							} else {
								InitDatasDaoImpl.getShipMakeToOrderDatas(THIS);
							}
							break;
						default:
							break;
						}
					} catch (Exception e) {
						FunctionOfActivity.makeToaskShow(THIS, "操作异常");
					}
				}
			} catch (Exception e) {
			}
		}

	};
}
